# conftest.py
import os
from typing import Any, Mapping
import pytest
import requests


@pytest.fixture(scope="session", autouse=True)
def base_url():
    """
    获取环境的基本 URL.
    """
    environment = os.getenv('ENVIRONMENT', 'admin')
    print(f"environment: {environment}")
    if environment == "dev":
        return 'https://127.0.0.1:9361'
    elif environment == "local":
        return 'https://127.0.0.1:9361'
    elif environment == "testing":
        return 'https://test.arknovv.net/cycling'
    elif environment == "prod":
        return 'https://test.arknovv.net/cycling'
    elif environment == "admin":
        return 'https://test.arknovv.net/cycling/admin'
    else:
        pytest.fail("Unknown environment. Use --env=dev|testing|prod")


class RequestRecorder:
    """
    记录HTTP请求详细信息的类.
    """

    def __init__(self):
        self.last_request = None

    def record(self, method: str, url: str, headers: Mapping[str, str] = None, data: Any = None, params: Any = None,
               json: Any = None, **kwargs):
        """Store the details of the last request."""
        self.last_request = {
            "method": method,
            "url": url,
            "headers": headers,
            "data": data,
            "params": params,
            "json": json,
            **kwargs,  # Include additional details like JSON body, cookies, etc.
        }


@pytest.fixture
def mock_requests(monkeypatch):
    """
    模拟所有 HTTP 方法（GET、POST、PUT、DELETE）的请求.
    """
    recorder = RequestRecorder()

    # 保存原始 HTTP 方法
    original_methods = {
        "GET": requests.get,
        "POST": requests.post,
        "PUT": requests.put,
        "DELETE": requests.delete,
    }

    def mock_method(method):
        """通用 mock 方法，支持 GET, POST, PUT, DELETE。"""

        def wrapper(url, params=None, json=None, headers=None, **kwargs):
            # 调用录制方法，记录请求
            recorder.record(method, url, params=params, json=json, headers=headers, **kwargs)
            # 调用原始的 requests 方法
            return original_methods[method](url, params=params, json=json, headers=headers, **kwargs)

        return wrapper

    # 替换 requests 的方法
    monkeypatch.setattr(requests, "get", mock_method("GET"))
    monkeypatch.setattr(requests, "post", mock_method("POST"))
    monkeypatch.setattr(requests, "put", mock_method("PUT"))
    monkeypatch.setattr(requests, "delete", mock_method("DELETE"))

    return recorder


@pytest.fixture(scope="session", autouse=True)
def global_params() -> dict:
    """
    提供在整个测试会话中使用的全局参数, 任何测试用例都可以更新和访问这些参数.
    @:return: 包含测试会话的全局参数的字典
    @:type dict
    """
    return {
        "user_id": None,
        "token": None,
        "refresh_token": None,
        "X-Project-id": "1853738518149468160",
        "channelId": "1853738518149468160",
        "cycling_id": None,
        "page_size": 10,
        "page_index": 1,
        "project_id": None,
        "product_id": None,
        "module_id": None,
        "version_id": None,
        "combination_version_id": None
    }
